<template>
	<div class="picture-list">
		<!-- 图片列表 -->
		<a-list
			:grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4, xl: 5, xxl: 6 }"
			:data-source="dataList"
			:loading="loading"
		>
			<template #renderItem="{ item: picture }">
				<a-list-item style="padding: 0">
					<!-- 单张图片 -->
					<a-card hoverable @click="doClickPicture(picture)">
						<template #cover>
							<img
								:alt="picture.name"
								:src="picture.thumbnailUrl ?? picture.url"
								style="height: 180px; object-fit: cover"
							/>
						</template>
						<a-card-meta :title="picture.name">
							<template #description>
								<a-flex>
									<a-tag color="green">
										{{ picture.category ?? '默认' }}
									</a-tag>
									<a-tag v-for="tag in picture.tags" :key="tag" color="blue">
										{{ tag }}
									</a-tag>
								</a-flex>
							</template>
						</a-card-meta>
						<template #actions>
							<a-tooltip title="分享">
								<ShareAltOutlined @click="(e) => doShare(picture, e)" />
							</a-tooltip>
							<a-tooltip title="以图搜图">
								<SearchOutlined @click="(e) => doSearch(picture, e)" />
							</a-tooltip>
							<a-tooltip title="编辑" v-if="canEdit">
								<EditOutlined @click="(e) => doEdit(picture, e)" />
							</a-tooltip>
							<a-tooltip title="删除" v-if="canDelete">
								<DeleteOutlined @click="(e) => doDelete(picture, e)" />
							</a-tooltip>
						</template>
					</a-card>
				</a-list-item>
			</template>
		</a-list>

		<!-- 分页组件 -->
		<div v-if="showPagination && (total ?? 0) > 0" class="pagination-wrapper">
			<a-pagination
				:current="current"
				:page-size="pageSize"
				:total="total ?? 0"
				:show-size-changer="true"
				:show-total="(total: number) => `总共 ${total} 条`"
				@change="handlePageChange"
				@show-size-change="handlePageChange"
			/>
		</div>

		<ShareModal ref="shareModalRef" title="分享图片" :link="shareLink" />
	</div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { ShareAltOutlined, SearchOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { deletePictureUsingPost } from '@/api/pictureController'
import { message, Modal } from 'ant-design-vue'
import { ref } from 'vue'
import ShareModal from '@/components/modal/ShareModal.vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore'

interface Props {
	dataList: API.PictureVO[]
	loading?: boolean
	showOperations?: boolean
	onReload?: () => void
	canEdit?: boolean
	canDelete?: boolean
	// 分页相关属性 - 简化版本
	showPagination?: boolean
	total?: number
	current?: number
	pageSize?: number
	onPageChange?: (current: number, pageSize: number) => void
}

const props = withDefaults(defineProps<Props>(), {
	dataList: () => [],
	loading: false,
	showOperations: false,
	showPagination: false,
	canEdit: false,
	canDelete: false,
	total: 0,
	current: 1,
	pageSize: 10,
})

// 分页变化处理
const handlePageChange = (current: number, pageSize: number) => {
	props.onPageChange?.(current, pageSize)
}

const router = useRouter()
const loginUserStore = useLoginUserStore()

// 检查登录状态的通用函数
const checkLoginStatus = (): boolean => {
	if (!loginUserStore.isLoggedIn()) {
		Modal.confirm({
			title: '请先登录',
			content: '您需要登录后才能进行此操作，是否前往登录页面？',
			okText: '去登录',
			cancelText: '取消',
			onOk: () => {
				router.push('/user/login')
			},
		})
		return false
	}
	return true
}

const doClickPicture = (picture: API.Picture) => {
	// console.log('点击图片', picture)
	// 跳转到图片详情页
	router.push({
		path: `/picture/${picture.id}`,
	})
}

// 以图搜图
const doSearch = (picture: API.Picture, event: MouseEvent) => {
	// 阻止事件冒泡，避免触发列表项的点击事件
	event.stopPropagation()
	// 检查登录状态
	if (!checkLoginStatus()) {
		return
	}
	// 跳转到搜索页面
	window.open(`/search_picture?pictureId=${picture.id}`)
}

// 编辑图片
const doEdit = (picture: API.Picture, event: MouseEvent) => {
	// 阻止事件冒泡，避免触发列表项的点击事件
	event.stopPropagation()
	// 检查登录状态
	if (!checkLoginStatus()) {
		return
	}
	// 跳转到编辑页面
	router.push({
		path: `/add_picture`,
		query: { id: picture.id, spaceId: picture.spaceId },
	})
}

// 删除图片
const doDelete = async (picture: API.Picture, event: MouseEvent) => {
	// 阻止事件冒泡，避免触发列表项的点击事件
	event.stopPropagation()
	// 检查登录状态
	if (!checkLoginStatus()) {
		return
	}
	const id = picture.id
	if (!id) {
		return
	}

	// 显示确认对话框
	Modal.confirm({
		title: '确认删除',
		content: `确定要删除图片"${picture.name}"吗？此操作不可撤销。`,
		okText: '删除',
		okType: 'danger',
		cancelText: '取消',
		onOk: async () => {
			try {
				const res = await deletePictureUsingPost({ id })
				if (res.data.code === 0) {
					message.success('删除成功')
					props.onReload?.()
				} else {
					message.error('删除失败：' + res.data.message)
				}
			} catch (error) {
				message.error('删除失败，请重试' + error)
			}
		},
	})
}

// 分享图片
const shareModalRef = ref()
const shareLink = ref('')
const doShare = (picture: API.Picture, event: MouseEvent) => {
	// 阻止事件冒泡，避免触发列表项的点击事件
	event.stopPropagation()
	// 检查登录状态
	if (!checkLoginStatus()) {
		return
	}
	// 设置分享链接
	shareLink.value = `${window.location.protocol}//${window.location.host}/picture/${picture.id}`
	if (shareModalRef.value) {
		// 打开分享模态框
		shareModalRef.value.openModal()
	}
}
</script>

<style scoped lang="scss">
.pagination-wrapper {
	display: flex;
	justify-content: flex-end;
	margin-top: 16px;
}
</style>
